class Loader {
	/**
	 * 判断本地文件是否存在
	 * @param {Object} localUrl
	 */
	isFileExists(localUrl) {
		// void plus.io.resolveLocalFileSystemURL( url, succesCB, errorCB );
		return new Promise((resolve) => {
			var localFilePath = plus.io.convertLocalFileSystemURL(localUrl);
			console.log(`判断绝对路径：${localFilePath}`);
			plus.io.resolveLocalFileSystemURL(localFilePath, (entry) => {
				resolve(true);
			}, (entry) => {
				resolve(false)
			});
		});
	}
	/**
	 * 获取文件的base64编码字符串
	 * @param {Object} localFilePath
	 */
	getFileBase64(localFilePath) {
		return new Promise((resolve) => {
			var reader = new plus.io.FileReader();
			reader.onload = function(e) {
				resolve(e.target.result)
			}
			reader.onerror = function() {
				resolve('');
			}
			reader.readAsDataURL(localFilePath);
		});
	}
	/**
	 * 获取文件名
	 * @param {Object} url
	 */
	getFileName(url) {
		return url.substring(url.lastIndexOf("/") + 1);
	}

	/**
	 * 下载文件
	 * @param {string} url 资源url地址
	 * @param {string} localUrl 下载时的相对完整路径 如 _downloads/test/PC_7ac6a6d319ba4ae29b38e5e4280e9122.png
	 * @return {string} localPath 返回平台绝对完整路径 如 /var/mobile/Containers/Data/Application/1956C299-53F5-4D8E-AFBF-C6BC72F34658/Library/Caches/Pandora/downloads/test/PC_7ac6a6d319ba4ae29b38e5e4280e9122.png
	 */
	downloadFile(url, localUrl) {
		return new Promise(async (resolve) => {
			const exists = await this.isFileExists(localUrl);
			console.log(`exists:${exists}`)
			if (exists) {
				resolve(plus.io.convertLocalFileSystemURL(localUrl));
			} else {
				var downloader = plus.downloader.createDownload(url, {
					filename: localUrl
				}, (downloaderObj, status) => {
					if (status == 200) {
						console.log(`下载完成：${downloaderObj.filename}`)
						resolve(plus.io.convertLocalFileSystemURL(downloaderObj.filename));
					} else {
						console.log(`下载失败：${downloaderObj.filename}`)
						resolve("");
					}
				});
				downloader.start();
			}
		})
	}
	constructor() {

	}
}
const loader = new Loader();
export default loader
